<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SseEmitter</title>
</head>
<body>
<button onclick="closeSse()">关闭连接</button>
<!--<button onclick="openSse()">新建连接</button>-->
<button onclick="sendData('event_one')">触发 event_one</button>
<button onclick="sendData('event_two')">触发 event_two</button>
<div id="message"></div>
</body>
<script>
    let source = null;

    // 用时间戳模拟登录用户
    const userId = new Date().getTime()

    if (!!window.EventSource) {

        let clientId

        // 建立连接
        // todo 携带 cookie
        source = new EventSource('http://127.0.0.1:8081/sse-aggregation/CreateSseConnect?event_types=event_one,event_two');

        /**
         * 连接一旦建立，就会触发 open 事件
         * 另一种写法：source.onopen = function (event) {}
         */
        source.addEventListener('open', e => {
            console.log('sse open', e)
            setMessageInnerHTML("建立连接...")
        }, false)

        source.addEventListener('client_id', e => {
            console.log('sse client_id', e)
            this.clientId = e.data
            setMessageInnerHTML(`获取 clientId: ${this.clientId}`)
        })

        source.addEventListener('event_one', e => {
            setMessageInnerHTML(`event_one message ${e.data}`)
        })

        source.addEventListener('event_two', e => {
            setMessageInnerHTML(`event_two message ${e.data}`)
        })

        /**
         * 客户端收到服务器发来的数据
         * 另一种写法：source.onmessage = function (event) {}
         */
        source.addEventListener('message', e => {
            console.log('sse message', e)
            setMessageInnerHTML(e.data)
        })


        /**
         * 如果发生通信错误（比如连接中断）, 就会触发 error 事件
         * 或者：
         * 另一种写法：source.onerror = function (event) {}
         */
        source.addEventListener('error', e => {
            if (e.readyState === EventSource.CLOSED) {
                setMessageInnerHTML("连接关闭")
            } else {
                console.log('sse error', e)
            }
        }, false);

    } else {
        setMessageInnerHTML("你的浏览器不支持 SSE")
    }

    // 监听窗口关闭事件，主动去关闭 sse 连接，如果服务端设置永不过期，浏览器关闭后手动清理服务端数据
    window.onbeforeunload = () => {
        closeSse()
    }

    function sendData(event_type) {
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', `http://127.0.0.1:8081/sse-aggregation/SendData?event_type=${event_type}`, true);
        httpRequest.send()
        console.log('send_data', httpRequest)
    }

    // 关闭 Sse 连接
    closeSse = () => {
        if (this.clientId) {
            source.close()
            const httpRequest = new XMLHttpRequest()
            httpRequest.open('GET', `http://127.0.0.1:8081/sse-aggregation/CloseSseConnect/?clientId=${this.clientId}`, true)
            httpRequest.send()
            console.log("close_sse", httpRequest)
        }
    }

    // 将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>'
    }
</script>
</html>
